'use strict'

###*
 # @ngdoc directive
 # @name xoceanApp.directive:addModule
 # @description
 # # addModule
 # Used in the directive 'template-box' for adding a module.
###
angular.module('xoceanApp')
  .directive('addModule', (ngDialog, $compile, $window)->
    restrict: 'EA'
    replace: true
    link: (scope, element, attrs) ->

      # hover
      element.on 'mouseenter', (e)->
        parent = (element)->
          _ele = element.parent()
          return if not _ele or _ele.hasClass('ntes-html')
          _ele.removeClass('hover')
          parent(_ele)
          return
        parent(element)
        return 
      scope.chosenModule = {}
      scope.choose = (mod)->
        scope.chosenModule = mod
      scope.cancel = ->
        scope.chosenModule = {}
        return true
      scope.chooseModule = ->
        if scope.chosenModule.url
          moduleHtml = """
            <div include="'#{scope.chosenModule.url}'" ></div>
          """
        else if scope.chosenModule.html
          moduleHtml = scope.chosenModule.html
        else 
          return false

        if not attrs.child
          moduleHtml = """
            <div add-module class="cms-add-module center-block ntes-hide">+</div>
            #{moduleHtml}
            <div add-module class="cms-add-module center-block ntes-hide">+</div>
          """
        try
          $window['currentElement'].after $compile(moduleHtml)(scope)
        catch e
          alert('添加模块失败！')
          return false
        
        $window['currentElement'].remove()
        return true
      element.on 'click', (e)->
        e.preventDefault()

        $window['currentElement'] = element
        # 增加模块
        scope.child = if attrs.child then true else false
        addModuleDialog = ngDialog.open({
          template: 'dialog3'
          scope: scope
          className: 'ngdialog-module'
        })
        addModuleDialog.closePromise.then ()->
          delete $window['currentElement']

        return

      return false
  )
